package org.six11.olive3.server;

import static org.six11.olive3.server.DatabaseThing.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.six11.olive3.picturephone.server.Find;
import org.six11.olive3.picturephone.server.TodoBatch;
import org.six11.util2.Debug;

import static org.six11.olive3.server.WebActionServlet.*;

/**
 * 
 * 
 * @author Gabe Johnson <johnsogg@cmu.edu>
 */
public class LoginHandler extends WebActionHandler {

  public LoginHandler(String jspPage, WebActionServlet webActionServlet) {
    super(jspPage, webActionServlet);
  }

  /**
   * 
   */
  @Override
  public void service(HttpServletRequest req, HttpServletResponse resp, ServletContext context)
      throws ServletException, IOException {
    HttpSession session = req.getSession();

    String userName = req.getParameter(PARAM_USER);
    String password = req.getParameter(PARAM_PASS);

    Map<String, String> vals = webActionServlet.getDbThing().getRow(SqlStrings.FIND_USER_BY_NAME,
        userName);
    if (userName == null && password == null) {
      go(req, resp, context);
    } else if (vals != null && userName.equals(vals.get("name")) && password.equals(vals.get("pass"))) {
      Debug.out("LoginHandler", "User " + vals.get("name") + " logged in.");
      session.setAttribute(SESSION_USER_NAME, userName);
      session.setAttribute(SESSION_USER_ID, vals.get("id"));
      int uid = new Integer(vals.get("id")).intValue();
      Map<String, String> potential = getPotential(uid);
      req.setAttribute("rate", potential.get("rate"));
      req.setAttribute("sketch", potential.get("sketch"));
      req.setAttribute("describe", potential.get("describe"));
      // new TodoBatch(webActionServlet.getDbThing()).processUserInBackgroundThread(uid);
      new Find(webActionServlet.getDbThing()).findAllToDoInBackground("" + uid);
      forwardTo("/main.jsp", req, resp, context);
    } else {
      if (vals != null && userName.equals(vals.get("name"))) {
        // user exists; wrong password
        Debug
            .out("LoginHandler", "User " + vals.get("name")
                + " exists but the password is wrong: '" + password + "' vs '" + vals.get("pass")
                + "'");
        req.setAttribute("errorMsg", "User exists but password is wrong. Sorry.");
      } else {
        Debug.out("LoginHandler", "User " + userName
            + " does not seem to be in the database.");
        req.setAttribute("errorMsg",
            "User isn't in the database. Perhaps the poking fleas are to blame?");
        // TODO
      }
      go(req, resp, context);
    }
  }
  


  private void bug(String what) {
    Debug.out("LoginHandler", what);
  }
}
